package pers.mine.service.impl;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pers.mine.po.GoodsItem;
import pers.mine.po.Member;
import pers.mine.po.Order;
import pers.mine.po.Ordergoods;
import pers.mine.service.inter.CheckOutService;
import pers.mine.service.inter.GoodsItemService;
import pers.mine.service.inter.MemberService;
import pers.mine.service.inter.OrderService;
import pers.mine.service.inter.OrdergoodsService;
import pers.mine.vo.Cart;

/**
 * @author Mine
 * @since 2016年10月20日_下午11:01:56
 */
@Service
public class CheckOutServiceImpl implements CheckOutService {
	@Autowired
	MemberService memberService;
	@Autowired
	GoodsItemService goodsItemService;
	@Autowired
	OrderService orderService;
	@Autowired
	OrdergoodsService ordergoodsService;

	/*
	 * @see pers.mine.service.inter.CheckOutService#doCheck(pers.mine.po.Member,
	 * pers.mine.vo.Cart)
	 */
	@Override
	public Order doCheck(Integer mid, Cart cart, boolean valiBalance) {
		if (mid != null && mid.intValue() > 0) {
			Member member = memberService.getOneMemberByID(mid);
			System.out.println(member);
			if (this.baseVali(member, cart, valiBalance)) {// 不需要验证余额
															// 循环验证购物车每件商品数是否合法
				for (GoodsItem one : cart.getGoodsItemList()) {
					GoodsItem dbOne = goodsItemService.getOneGoodsItemByID(one
							.getId());
					if (dbOne.getState().intValue() == 1
							&& one.getNum().intValue() > dbOne.getNum()
									.intValue()) {
						// ps:商品必须在售且库存足够
						return null;// 验证失败
					}
				}
				return this.getOrder(member, cart);
			}
		}
		return null;// 验证失败
	}

	/*
	 * @see
	 * pers.mine.service.inter.CheckOutService#checkOut(pers.mine.po.Member,
	 * pers.mine.vo.Cart)
	 */
	@Override
	// 事务注解
	@Transactional(rollbackFor = { SQLException.class, RuntimeException.class })
	public boolean checkOut(Order order) throws SQLException {
		if (order == null) {
			return false;
		}
		Cart cart = order.getRawCart();
		if (cart == null || cart.getNumSum() < 1) {
			return false;
		}
		Integer mid = order.getMid();
		if (this.doCheck(mid, cart, true) == null) {
			System.out.println("订单数据验证失败。。。");
			return false;
		}
		/**
		 * 尝试修改用户余额
		 */
		Member member = memberService.getOneMemberByID(mid);
		double newBanlance = member.getBalance().doubleValue()
				- order.getCost().doubleValue();
		if (!memberService.setMemberBalance(mid, newBanlance)) {
			System.out.println("尝试修改用户余额失败!!![操作:#" + mid + "号用户余额修改>>>"
					+ newBanlance + "(￥)]");
			throw new SQLException();
		}
		/**
		 * 尝试插入订单信息并返回定单号
		 */
		if (!orderService.addOrder(order)) {
			if (order.getId() == null) {// 验证订单号
				System.out.println("订单号没有正常获取到...");
				throw new SQLException();
			}
		}
		System.out.println(order);
		/**
		 * 尝试循环修改商品库存
		 */
		int id = 0;
		for (GoodsItem oneGoods : cart.getGoodsItemList()) {
			Integer gid = oneGoods.getId();
			Integer differenceNum = oneGoods.getNum();
			id = gid;
			if (!goodsItemService.setGoodsInventoryByDifference(gid,
					differenceNum)) {
				System.out.println("修改库存失败![操作:#" + gid + "号商品库存差值>>>"
						+ differenceNum + "(件)]");
				throw new SQLException();
			}
		}
		System.out.println(goodsItemService.getOneGoodsItemByID(id));
		/**
		 * 尝试写入订单商品表
		 */
		// 先根据订单id、商品list生成成订单商品list
		List<Ordergoods> ls = Ordergoods.createOrdergoodsList(order.getId(),
				cart.getGoodsItemList());
		System.out.println(ls);
		if (!ordergoodsService.addOrdergoods(ls)) {
			System.out.println("写入订单商品表失败!");
			throw new SQLException();
		}
		return true;
	}

	/**
	 * 依据用户以及购物车信息获取一份订单
	 * 
	 * @param member
	 * @param cart
	 * @return
	 */
	private Order getOrder(Member member, Cart cart) {
		Order order = new Order();
		order.setMid(member.getId());
		order.setTel(member.getTel());
		order.setAddress(member.getAddress());
		order.setSum(cart.getNumSum());
		order.setCost(cart.getPriceSum());
		// 订单时间在提交数据库的时候自己添加
		// 生成简要商品信息
		StringBuilder desc = new StringBuilder();
		int i = 1;
		int size = cart.getGoodsItemList().size();
		for (GoodsItem one : cart.getGoodsItemList()) {
			desc.append("[#" + one.getId() + "号商品_" + one.getName() + "_("
					+ one.getNum() + ")件]");
			if (i == size) {
				desc.append("。");
			} else if (i < 5) {
				desc.append("、");
			} else {
				desc.append(".....");
				break;
			}
			i++;
		}
		order.setRawCart(cart);// 保存原始cart
		order.setDesc(desc.toString());
		return order;
	}

	/**
	 * 基本信息验证,可以控制是否验证账户余额
	 */
	private boolean baseVali(Member member, Cart cart, boolean valiBalance) {
		if (member != null || cart != null) {
			if (member.getId() != null && member.getId() > 1) {
				if (member.getState() != null && member.getState() == 1) {
					if (member.getBalance() != null && member.getBalance() >= 0) {
						if (member.getTel() != null
								&& !"".equals(member.getTel().trim())) {
							if (member.getAddress() != null
									&& !"".equals(member.getAddress().trim())) {
								if (cart != null && cart.getNumSum() > 0) {
									if (valiBalance) {// 判断余额是否验证
										if (cart.getPriceSum() <= member
												.getBalance().doubleValue()) {
											return true;
										} else {
											return false;
										}
									}
									return true;
								}
							}
						}
					}
				}
			}
		}
		return false;
	}

}
